package com.backend.system.service.processors.permission;

import cn.hutool.core.bean.BeanUtil;
import com.backend.system.beans.permission.PermissionAddOrUpdateReq;
import com.backend.system.common.CustomException;
import com.backend.system.common.annotation.ProcessorBean;
import com.backend.system.common.enums.ActionTypeEnum;
import com.backend.system.common.processor.AbstractProcessorTemplate;
import com.backend.system.common.processor.ProcessorContext;
import com.backend.system.dao.entity.Permission;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * 新增或修改权限处理器
 *
 * @author backend-manage
 */
@Slf4j
@Component
@ProcessorBean(action = ActionTypeEnum.PERMISSION_ADD_OR_UPDATE)
public class PermissionAddOrUpdateProcessor extends AbstractProcessorTemplate<PermissionAddOrUpdateReq, Boolean> {

    private Permission permission;

    private boolean isUpdatePermission;

    @Override
    protected void init(ProcessorContext<PermissionAddOrUpdateReq> context) {
        PermissionAddOrUpdateReq req = context.getData();
        permission = null;
        isUpdatePermission = Objects.nonNull(req.getId());

        if (isUpdatePermission) {
            permission = permissionService.getById(req.getId());
            if (Objects.isNull(permission)) {
                throw CustomException.argsError("权限不存在");
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean handle(ProcessorContext<PermissionAddOrUpdateReq> context) {
        PermissionAddOrUpdateReq req = context.getData();
        boolean result;

        // 更新权限
        if (isUpdatePermission) {
            BeanUtil.copyProperties(req, permission);
            result = permissionService.updateById(permission);
        } else {
            // 新增权限
            permission = new Permission();
            BeanUtil.copyProperties(req, permission);
            result = permissionService.save(permission);
        }
        return result;
    }
}
